<template>
  <div class="search-container">
    <van-sticky>
      <form action="/">
        <van-search
          v-model.trim="searchText"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="onCancel"
          background="#3296fa"
          @focus="isShowResults=false"

        />
      </form>

    </van-sticky>
    <!--    搜索结果-->
    <SearchResults :searchText="searchText" v-if="isShowResults"></SearchResults>
    <!--    搜索历史-->
    <SearchHistory @search="onSearch" v-else-if="!searchText" :history="history"></SearchHistory>
    <!--    联想建议-->
    <SearchSuggestion :searchText="searchText" v-else @clickSuggestionItem="onSearch"></SearchSuggestion>

  </div>
</template>

<script>
import SearchHistory from './components/Search-history'
import SearchSuggestion from './components/Search-suggestion'
import SearchResults from './components/Search-results.vue'
import { getItem, setItem } from '@/utils/storage'

export default {
  name: 'Search',
  data () {
    return {
      searchText: '',
      isShowResults: false,
      history: getItem('HMTT-HISTORY') || []
    }
  },
  watch: {
    history: {
      deep: true,
      handler (val) {
        setItem('HMTT-HISTORY', val)
      }
    }
  },
  methods: {
    // 回车或手机键盘点击搜索 或点击联想item
    onSearch (val) {
      this.searchText = val
      this.isShowResults = true
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
    },
    // 点击取消
    onCancel () {
      this.$router.back()
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  }
}
</script>

<style scoped lang='less'>
.search-container {
  .van-search__action {
    color: #ffffff;
  }
}
</style>
